import { ref } from 'vue';
import { createGlobalState } from '@vueuse/core';
import {
  addDisableProperty,
  listToEnum,
  listToOption,
  treeToEnum,
} from '@/utils/utils';
import { getDictType } from '@/api/monitor';
import { getModel, getProjectTree } from '@/api/push';

export const pushStore = createGlobalState(() => {
  // 字典-设备类型
  const deviceModeOptions = ref<Global.Option[]>([]);
  const deviceModeEnum = ref<Record<string, any>>({});
  const getDeviceModeDict = () => {
    getDictType('sys_device_mode').then((res: any) => {
      deviceModeOptions.value = listToOption(
        res.data as any[],
        'dictLabel',
        'dictValue',
      );
      deviceModeEnum.value = listToEnum(
        res.data as any[],
        'dictValue',
        'dictLabel',
      );
    });
  };

  // 获取-设备型号
  const getModelOptions = ref<Global.Option[]>([]);
  const getModelEnum = ref<Record<string, any>>({});
  const getDeviceModels = async () => {
    const res = await getModel();
    if (res.code == 200) {
      getModelOptions.value = listToOption(
        res.data as any[],
        'model',
        'modelId',
      );
      getModelEnum.value = listToEnum(res.data as any[], 'modelId', 'model');
    }
  };

  // 获取-项目名称
  const projectList: any = ref([]);
  const projectEnum: any = ref({});
  const getProjectList = async () => {
    const list = JSON.parse(sessionStorage.getItem('projectList') || 'null');
    const Enum = JSON.parse(sessionStorage.getItem('projectEnum') || 'null');
    if (Array.isArray(list)) {
      projectList.value = list;
      projectEnum.value = Enum;
      return;
    }
    const res = await getProjectTree();
    if (res.code == 200) {
      projectList.value = addDisableProperty(res.data);
      sessionStorage.setItem('projectList', JSON.stringify(projectList.value));
      projectEnum.value = treeToEnum(projectList.value, {
        label: 'label',
        value: 'id',
      });
      sessionStorage.setItem('projectEnum', JSON.stringify(projectEnum.value));
    }
  };
  const refreshStore = {
    onPush() {
      getDeviceModeDict();
      getDeviceModels();
      getProjectList();
    },
  };
  return {
    refreshStore,
    deviceModeOptions,
    deviceModeEnum,
    getModelOptions,
    getModelEnum,
    projectList,
    projectEnum,
  };
});
